import {ChangeDetectionStrategy, Component, inject, signal} from '@angular/core';
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {FormControl, FormsModule, ReactiveFormsModule, Validators} from "@angular/forms";
import {MatIcon} from "@angular/material/icon";
import {MatButton} from "@angular/material/button";
import {userApi} from "../../api/user";
import {SelfHttp} from "../../services/http/service";
import Cookies from "js-cookie";
import {SelfDialogWrap} from "../../services/http/selfDialogWrap";
import {SiteService} from "../../services/site/site.service";

@Component({
  selector: 'app-login',
  imports: [MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule, MatIcon, MatButton],
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [SelfHttp, SelfDialogWrap, SiteService]
})
export class LoginComponent {
  constructor(private selfHttp: SelfHttp, private selfDialogWrap: SelfDialogWrap, private siteService: SiteService) {
  }

  /*用户名*/
  readonly username = new FormControl('', [Validators.required]);
  errorUserMessage = signal('');
  updateErrorUsername() {
    if (this.username.hasError('required')) {
      this.errorUserMessage.set('请输入用户名');
    } else {
      this.errorUserMessage.set('');
    }
  };

  /*密码*/
  readonly password = new FormControl('', [Validators.required]);
  errorPasswordMessage = signal('');
  updateErrorPassword() {
    if (this.password.hasError('required')) {
      this.errorPasswordMessage.set('请输入密码');
    } else {
      this.errorPasswordMessage.set('');
    }
  };

  /*登录*/
  login() {
    if (this.username.hasError('required') || this.password.hasError('required')) {
      this.updateErrorUsername();
      this.updateErrorPassword();
      return;
    }
    const form = {
      username: this.username.value,
      pwd: this.password.value
    }
    this.selfHttp.post(userApi.login, form, (res: any) => {
      Cookies.set("token", res);
      if(res){
        const info = {
          username: this.username.value,
          accessToken: res
        }
        const infoStr = JSON.stringify(info);
        Cookies.set("authorized-token", infoStr);
        localStorage.setItem('userInfo', infoStr);
      }
      this.siteService.getSiteInfo(() => {
        this.selfDialogWrap.openDialog('登录成功', 'toast', () => {
          window.location.href = '/';
        })
      });
    })
  }
}
